package com.zsj.juc.Atomic;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @author zsj
 * @version 1.0
 * @date 2024/5/17 14:58
 * @description 原子类属性修改
 */
@Data
@AllArgsConstructor
class BankAccount {
    String name;
    volatile int count;//需要被修改的属性 需要volatile修饰
}

public class AtomicFieldUpdater {

    private static final Logger log = LoggerFactory.getLogger(AtomicFieldUpdater.class);

    public static void main(String[] args) throws InterruptedException {
        BankAccount bankAccount = new BankAccount("cab", 0);
        //以线程安全的方法 修改非线程安全的对象
        AtomicIntegerFieldUpdater<BankAccount> fieldUpdater
                = AtomicIntegerFieldUpdater.newUpdater(BankAccount.class, "count");
        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    for (int j = 0; j < 1000; j++) {
                        fieldUpdater.getAndIncrement(bankAccount);
                    }
                } finally {
                    countDownLatch.countDown();
                }

            }, "" + i).start();
        }
        countDownLatch.await();
        log.info("{}", bankAccount.count);
    }


}
